import urllib
import datetime
import time

import MSLogger
import MSData

def now():
    return datetime.datetime.fromtimestamp(time.time())
def nowPastTenMinutes():
    return now() - datetime.timedelta(0, 600)

def getBeginEnd(LastEvent):
    begin = None
    if LastEvent != None:
        begin = LastEvent.eventReceiveTime
    else:
        begin = nowPastTenMinutes()
    end = now()
    return (begin.strftime(MSData.TIME_FORMAT_MAGIC), end.strftime(MSData.TIME_FORMAT_MAGIC))

def parseEventLine(EventLine):
    s = EventLine.split('/>')[0]
    s = s.split('<')[1]
    s = s.split(' ')
    e = {}
    for prop in s[1:len(s)]:
        prop = prop.split('=')
        e[prop[0]] = prop[1].replace('"', '')
    #e['eventInternalId'] = EventId
    return e



class Reader:
    def __init__(self):
        return

    def connect(self):
        return True

    def forceConnection(self):
        return True

    def readEvents_PGSM(self, MSObjects):
        for obj in MSObjects:
            try:
                    #basing upon last event calculate time range to process
                timeRange = getBeginEnd(obj.lastEvent_PGSM)
                    #read events from API
                events    = readURLData('events', obj.objectSKey, timeRange)
                    #TBD Offline alarm here
                    #check events size
                if not events:
                    continue

                processed = 0
                for s in events:
                    try:
                        eventSplitted = parseEventLine(s)
                        e = MSData.MSEvent()
                        e.fromPGSM(eventSplitted)
                        e.objectId = obj.objectId_PCN
                        obj.eventsPGSM.append(e)
                        if e.eventGenerateTime > timeRange[0]:
                            MSLogger.logError('Reader: PGSM: received events(%s) when requested (%s:%s)' % (e.eventGenerateTime, timeRange[0], timeRange[1]))
                    except Exception, err:
                        MSLogger.logError('Reader: PGSM: event processing failed: event(%s) error(%s)' % (str(e), str(err)))
                        continue
                obj.eventsPGSM.sort()
                obj.lastEvent_PGSM = obj.eventsPGSM[len(obj.eventsPGSM)-1]
            except Exception, err:
                MSLogger.logError('Reader: PGSM: object processing failed: error(%s)' % (str(err)))
                continue

    def readEvents_ContactId(self, MSObjects):
        for obj in MSObjects:
            try:
                    #basing upon last event calculate time range to process
                timeRange = getBeginEnd(obj.lastEvent_ContactId)
                    #read events from API
                events    = readURLData('contactId', obj.objectSKey, timeRange)
                    #TBD Offline alarm here
                    #check events size
                if not events:
                    continue

                processed = 0
                for s in events:
                    try:
                        eventSplitted = parseEventLine(s)
                        e = MSData.MSEvent()
                        e.fromContactId(eventSplitted)
                        e.objectId = obj.objectId_PCN
                        obj.eventsContactId.append(e)
                        if e.eventGenerateTime > timeRange[0]:
                            MSLogger.logError('Reader: ContactId: received events(%s) when requested (%s:%s)' % (e.eventGenerateTime, timeRange[0], timeRange[1]))
                    except Exception, err:
                        MSLogger.logError('Reader: ContactId: event processing failed: event(%s) error(%s)' % (str(s), str(err)))
                        continue
                obj.eventsContactId.sort()
                obj.lastEvent_ContactId = obj.eventsContactId[len(obj.eventsContactId)-1]
            except Exception, err:
                MSLogger.logError('Reader: ContactId: object processing failed: error(%s)' % (str(err)))
                continue

    def readEvents_GPS(self, MSObjects):
        pass


